const mongo = require('mongodb');
const ObjectID = mongo.ObjectID;
const Grid = require('gridfs-stream');
const Busboy = require('busboy');
const crypto = require('crypto');

module.exports = {
  open:false,
  description:'上传文件',
  handler: (req, res, next)=>{
    let doc = req.body;
    let projectName = doc.projectName||{};
    const gfs = Grid(req.mongo, mongo);
    const busboy = new Busboy({headers: req.headers});
      const fsHash = crypto.createHash('md5');
    //第三方中间件接收上传
    req.pipe(busboy);
    busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
      let filesize = 0;
      const id = new ObjectID();
      const writestream = gfs.createWriteStream({
        _id: id,
        mode: "w",
        filename: filename,
        content_type: mimetype
      });
      file.pipe(writestream);
      file.on('end', function () {

        //console.log("end");
        const url = "/res/" + id+"/content";
        const fileObj = {
          _id: id,
          filename: filename,
          projectName:projectName,
          uploadTime:new Date(),
          filesize: Math.round(filesize/1000)+"KB",
          content_type: mimetype,
          url: url,
          md5:  fsHash.digest('hex')
        };
        res.json(fileObj);

        let fn = function () {

        };
        req.mongo.collection("file").insertOne(fileObj,fn);
      }).on('error', function (err) {
        console.log("err:" + err)
      }).on('data', function (data) {
        filesize += data.length;
          fsHash.update(data);
      });

    })
  }
};